var http = require('http');//包含、加载http模块  http本身是一个对象，那么肯定有方法，也有属性
var fs = require('fs');
var url = require('url');
var querystring = require('querystring');
var util = require('util');
var ip = "127.0.0.1";
var port = 80;
var siteName = "Wotoc's blog mqxgg";
var server = http.createServer(function (request, response) {
	// 发送 HTTP 头部 
	// HTTP 状态值: 200 : OK
	// 内容类型: text/plain
	//response.writeHead(200, {'Content-Type': 'text/html'});
	response.statusCode = 200 ;
	response.setHeader('Content-Type', 'text/html')

	var str =request.url.substr(request.url.lastIndexOf('.')+1);
	var strs = {
		'html':'text/html',
		'css':'text/css',
		'js':'text/javascript',
		'jpg':'image/jpeg'
	}
	if (strs[str]==null) {
		strs[str] = 'text/plain';
	}
	response.setHeader('Content-Type', strs[str])

	var data ='404';
	var p = url.parse(request.url,true);
	if(p.pathname == '/index.html'){try{
			data = fs.readFileSync('.'+request.url,'utf-8');
			data = data.replace(/%title/g,siteName)
			item = fs.readFileSync('data.json','utf-8');
			item = JSON.parse(item)
			var s = '';
			for (var i = 0; i < item.length; i++) {
				s+= '<div class="item">';
				s+='<h6>'+item[i].author+'<span>'+item[i].time+'</span></h6>';
				s+='<p>'+item[i].message+'<a href="/delmessage?id='+i+'">删除</a></p>';
				s+='</div>';
			}
			
			data = data.replace(/%main/g,s);
		}
		catch(e){
	
		}
		response.write(data)
		response.end();
	}else if(p.pathname == '/form.html'){
		data = fs.readFileSync('.'+request.url,'utf-8');
		data = data.replace(/%title/g,siteName)
		response.write(data)
		response.end();
	}else if(p.pathname == '/addmessage.html'){
		/*item = JSON.parse(fs.readFileSync('data.json','utf-8'));
		item.push({
			author:p.query.author,
			message:p.query.message,
			time:new Date()
		})
		item = JSON.stringify(item);
		fs.writeFileSync('data.json',item)
		response.writeHead(302,{
			'location':'/index.html'
		})*/
		var post=''
		request.on('data', function(chunk){    
	        post += chunk;
	    });
	    request.on('end', function(chunk){
	    	post = querystring.parse(post);
	    	item = JSON.parse(fs.readFileSync('data.json','utf-8'));
			item.push({
				author:post.author,
				message:post.message,
				time:new Date()
			})
			fs.writeFileSync('data.json',JSON.stringify(item))
			response.writeHead(302,{
				'location':'/index.html'
			})
			response.end();
	    });
	}else if(p.pathname == '/delmessage'){
		id = p.query.id
		item = JSON.parse(fs.readFileSync('data.json','utf-8'));
		item.splice(id,1)
		item = JSON.stringify(item);
		fs.writeFileSync('data.json',item)
		response.writeHead(302,{
			'location':'/index.html'
		})
		response.write(data)
		response.end();

	}
	// 发送响应数据 "Hello World"
}).listen(port);
// 终端打印如下信息
console.log('Server running at http://%s:%s/',ip,port);